package com.price.common.util

import android.content.Context
import android.content.SharedPreferences
import com.price.common.extend.context
import java.lang.reflect.Type

object SpUtils {

    private const val fileName = "shared_txt"
    var sharedPref: SharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)


    inline fun <reified T> put(key: String, value: T) {
        if (null == value) {
            clearKey(key)
            return
        }
        with(sharedPref.edit()) {
            val save = JsonUtils.toJson(value)
            putString(key, save)
            apply()
        }
    }

    inline fun <reified T> get(key: String, defaultValue: T? = null): T? {
        val str = sharedPref.getString(key, "")
        if (str.isNullOrEmpty()) {
            return defaultValue
        }
        return JsonUtils.fromJson(str, T::class.java)
    }

    fun <T> get(key: String, cls: Class<T>, defaultValue: T? = null): T? {
        val str = sharedPref.getString(key, "")
        if (str.isNullOrEmpty()) {
            return defaultValue
        }

        return JsonUtils.fromJson(str, cls)
    }

    fun <T> get(key: String, type: Type, defaultValue: T? = null): T? {
        val str = sharedPref.getString(key, "")
        if (str.isNullOrEmpty()) {
            return defaultValue
        }
        return JsonUtils.fromJson(str, type)!!
    }

    inline fun <reified T> getList(key: String, defaultValue: List<T>? = null): List<T>? {
        val str = sharedPref.getString(key, "")
        if (str.isNullOrEmpty()) {
            return defaultValue
        }
        return JsonUtils.jsonToList(str)
    }

    inline fun <reified K, reified V> getMap(key: String): Map<K, V>? {
        val str = sharedPref.getString(key, "")
        if (str.isNullOrEmpty()) {
            return null
        }
        return JsonUtils.jsonToMaps<K,V>(str)
    }

    fun clearAll() {
        sharedPref.edit().clear().apply()
    }

    fun clearKey(key: String) {
        sharedPref.edit().remove(key).apply()
    }
}